// pages/my/index.js

const {
  myApi,
  globalApi,
} = require('../../api/index')

const {
  USERVIEWTYPE
} = require('../../utils/util')


const app = getApp()
Page({
  /**
   * 页面的初始数据
   */
  data: {
    // 头部安全距离
    incomeNum: 0,
    incomeAmount: 0,
    tagListT: ['我的模型', '我的收藏', '我的训练'],
    tagActiveT: 0,
    IMGBASEURL: app.globalData.IMGBASEURL,
    dynamicStyle: 0, //头部安全距离
    dayStyle: 0, //用户头部定位后的安全距离
    isTitle: false, //滑动后头部的变化
    tabTop: 0, //tab的粘性定位距离
    draw: false,
    drawActive: false,
    active: 1,
    tabList: ['创作', '灵感', '模型'],
    isLoge: false,
    inspiration: 0, //算力值
    welfareMessge: {},
    user: {}, //用户信息
    attentionFansCollect: {}, //或获赞数
    pageIndex: 1,
    pageCount: 10,
    listData: [],
    leftList: [],
    rightList: [],
    lodding: false,
    id: "",
    visible: false,
    checkboxActive: "../../assets/login/checkbox_def.svg",
    signActive: 1,
    signList: {},
    vipGrade: "",
    imgVip: [
      "../../assets/my/yhdj_A1@2x.png",
      "../../assets/my/yhdj_A2@2x.png",
      "../../assets/my/yhdj_A3@2x.png",
      "../../assets/my/yhdj_A4@2x.png",
      "../../assets/my/yhdj_A5@2x.png",
      "../../assets/my/yhdj_A6@2x.png",
      "../../assets/my/yhdj_A7@2x.png",
    ],
    // roleAchievement: [
    //   "../../assets/my/jzdr_16.png",
    //   "../../assets/my/lgms_16.png",
    //   "../../assets/my/ptxs_16.png",
    // ],
    // identity: "试用会员",
    identityImg: USERVIEWTYPE,
    vipBackgroundImg: '',
    joiAssociationData: true,
    presentInspiration: 0
  },
  // 去扫码页
  toScanCode() {
    // 扫描二维码
    wx.scanCode({
      success(res) {
        console.log('扫码结果', res)
        if (res.result.includes('openuser')) {
          let code = res.result.split('openuser:')[1]
          wx.navigateTo({
            url: `/pages/my/othersPage/index?code=${code}`,
          })
        }
      }
    })
  },
  // 去我的二维码卡片
  toMyQRcode() {
    console.log('我的二维码');
    wx.navigateTo({
      url: '/pages/my/myQRcode/index',
    })
  },
  onDelet(e) {
    let arr = this.data.listData.filter(el => el.id != e.detail.id)
    this.setData({
      listData: arr
    })
  },

  loadMyModelList(e) {
    const index = e.currentTarget.dataset['index']
    this.setData({
      tagActiveT: index,
      listData: [],
      pageIndex: 1
    })
    this.init(3)
  },
  // eventName(e) {
  //   this.setData({
  //     draw: e.detail
  //   })
  // },
  // singtName(e) {
  //   this.setData({
  //     draw: false,
  //     inspiration: e.detail.inspiration,
  //   })
  // },
  // vip图片筛选
  vipGradeFun(value) {
    switch (value) {
      case "VIP001":
        return 0;
      case "VIP002":
        return 1;
      case "VIP003":
        return 2;
      case "VIP004":
        return 3;
      case "VIP005":
        return 4;
      case "VIP006":
        return 5;
      case "VIP007":
        return 6;
    }
  },
  // 会员等级背景筛选
  membershipLevel(grade) {
    let arr = ['', 'vip_normal bg@2x.png', 'vip_trial-bg@2x.png', 'vip_week-bg@2x.png', 'vip_month-bg@2x.png', 'vip_quarter-bg@2x.png', 'vip-year-bg@2x.png']
    this.setData({
      vipBackgroundImg: arr[grade.VIPWeight]
    })

  },
  handleSelected(e) {
    if (e.currentTarget.dataset.index == 2) {
      this.setData({
        isLoge: false,
        visible: false,
        id: "",
        active: 1,
        tab1: "tab-item tab-left tab-active",
        tab2: "tab-item",
        listData: [],
        leftList: [],
        rightList: [],
      })
      wx.clearStorageSync()
      this.getTabBar().setListData(false);

    } else if (e.currentTarget.dataset.index == 1) {
      this.setData({
        isLoge: false,
        visible: false
      })
      wx.navigateTo({
        url: '/pages/login/index',
      })
    } else if (e.currentTarget.dataset.index == 3) {
      this.setData({
        visible: false
      })
    }
  },
  changeUser(e) {
    this.setData({
      visible: true
    })
  },
  onVisibleChange(e) {
    this.setData({
      visible: e.detail.visible,
    });
  },
  onPullDownRefresh() {
    if (this.data.active == 1) {
      this.setData({
        tab1: "tab-item tab-left tab-active",
        tab2: "tab-item",
        listData: [],
        leftList: [],
        rightList: [],
        pageIndex: 1,
        active: 1
      })
      this.init(1)
    } else if (this.data.active == 2) {
      this.setData({
        tab1: "tab-item tab-left ",
        tab2: "tab-item tab-active",
        listData: [],
        leftList: [],
        rightList: [],
        pageIndex: 1,
        active: 2
      })
      this.init(2)
    }
  },
  // 礼物的显示隐藏
  inspiration() {
    this.setData({
      draw: "block"
    })

  },
  inspirationClose() {
    this.setData({
      draw: "none"
    })
  },
  // tab栏
  tabActive(e) {
    let index = e.currentTarget.dataset['value']
    this.setData({
      listData: [],
      leftList: [],
      rightList: [],
      pageIndex: 1,
      active: index
    })
    this.init(index)
  },

  // 查看列表详情
  particularsItem(e) {
    wx.previewImage({
      current: e.currentTarget.dataset.url.coverImage, // 当前显示图片的http链接
      urls: e.currentTarget.dataset.url.images // 需要预览的图片http链接列表
    })
    return
    // let thet = this
    // wx.navigateTo({
    //   url: `./particulars/particulars?id=${e.currentTarget.dataset.id}&active=${this.data.active}`
    // })
  },
  // 福利任务
  welfareTask(e) {
    console.log();
    wx.navigateTo({
      url: './welfareTask/welfareTask?id=' + e.currentTarget.dataset['id'],
    })
  },

  // 登录
  immediatelyLoge() {
    wx.navigateTo({
      url: '../login/index',
    })
  },
  splitArray(arr) {
    const mid = Math.ceil(arr.length / 2);
    const firstHalf = arr.slice(0, mid);
    const secondHalf = arr.slice(mid);
    return [firstHalf, secondHalf];
  },
  // 1 我的创作 2 我的收藏
  async init(value) {
    let cIndex = this.data.tagActiveT
    let thet = this
    thet.setData({
      lodding: false
    })
    if (value == 1) {
      myApi.getMyCreationPageList({
        userId: this.data.user.UserId,
        pageIndex: thet.data.pageIndex,
        pageCount: 10,
        orderCreationTime: false,
        creationTypeStr: '0',
      }).then((res => {
        thet.setData({
          listData: [...thet.data.listData, ...res.items],
          pageIndex: thet.data.pageIndex + 1
        })
        if (thet.data.listData.length >= res.totalCount) {
          thet.setData({
            lodding: true
          })
        }
      }))
    } else if (value == 2) {
      myApi.getmycollectionbypage({
        PageIndex: thet.data.pageIndex,
        PageSize: 10,
        KeyWord: ''
      }).then((res => {
        thet.setData({
          listData: [...thet.data.listData, ...res.Result.Datas],
          pageIndex: thet.data.pageIndex + 1
        })
        const rres = this.splitArray(res.Result.Datas)
        if (this.data.listData.length > 0) {
          this.setData({
            leftList: [...this.data.leftList, ...rres[0]],
            rightList: [...this.data.rightList, ...rres[1]],
          })
        }
        if (thet.data.listData.length >= res.Result.TotalCount) {
          thet.setData({
            lodding: true
          })
        }
      }))
    } else {
      let res
      if (cIndex == 0) {
        res = await myApi.getMyworlLlist({
          "bottomMoldType": "",
          "name": "",
          "PageIndex": thet.data.pageIndex,
          "PageSize": 10
        })
      }
      if (cIndex == 1) {
        res = await myApi.getaicollectionList({
          "PageIndex": this.data.pageIndex,
          "PageSize": 10
        })
      }
      if (cIndex == 2) {
        res = await myApi.getList({
          "PageIndex": this.data.pageIndex,
          "PageSize": 10
        })
      }

      this.setData({
        listData: [...this.data.listData, ...res.items],
        pageIndex: this.data.pageIndex + 1
      })
      if (this.data.listData.length >= res.totalCount) {
        this.setData({
          lodding: true
        })
      }
    }
    wx.stopPullDownRefresh();
  },
  onerror(e) {
    let user = this.data.user
    user.Avatar = this.data.IMGBASEURL + "user_64.png"
    this.setData({
      user: user
    })
  },
  readRend(id) {
    const arr = this.data.listData.filter((e) => e.ID != id)
    const rres = this.splitArray(arr)
    this.setData({
      leftList: rres[0],
      rightList: rres[1],
    })
  },

  // 点击不在提醒
  remind() {
    if (this.data.checkboxActive == "../../assets/login/checkbox_def.svg") {
      this.setData({
        checkboxActive: "../../assets/login/checkbox_sel.svg"
      })
    } else {
      this.setData({
        checkboxActive: "../../assets/login/checkbox_def.svg"
      })
    }
  },


  // 加入社群
  joiAssociation() {
    wx.navigateTo({
      url: './association/association',
    })
  },
  // 删除加入社群
  joiAssociationDelete() {
    this.setData({
      joiAssociationData: false
    })
  },
  succeedClose() {
    this.setData({
      drawActive: false
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    //  获取安全距离等
    wx.getSystemInfo({
      success: res => {
        let systemInfo = wx.getSystemInfoSync()
        let info = wx.getMenuButtonBoundingClientRect()
        this.setData({
          height: (info.top - systemInfo.statusBarHeight) * 2 + info.height,
          dynamicStyle: (res.statusBarHeight) + "px",
          dayStyle: (info.top - systemInfo.statusBarHeight) * 2 + info.height + res.statusBarHeight + "px",
          tabTop: (info.top - systemInfo.statusBarHeight) * 2 + info.height + res.statusBarHeight + "px"
        })
      },
      fail(err) {
        console.log(err);
      }
    })
    myApi.getcurrentusermodelincome().then(res => {
      this.setData({
        incomeNum: res.Result.TotalIncomeAmount,
        incomeAmount: res.Result.TotalIncomeNumber,
      })
    })
  },

  onPageScroll: function (event) {
    const app = getApp()
    let tab = wx.createSelectorQuery()
    tab.select('#tab').boundingClientRect((res) => {
      if (res.top > app.globalData.navHeight + 44) {
        this.setData({
          isTitle: false
        })
      } else {
        this.setData({
          isTitle: true
        })
      }
    }).exec()
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getTabBar().init();
    this.setData({
      vipGrade: this.vipGradeFun(wx.getStorageSync('userInfo').VIPLevelCode),
      // identity: this.identityFun(wx.getStorageSync('userInfo').VIPLevelName),
    })
    this.getTelepathy()
    let user = wx.getStorageSync('userInfo')

    let thet = this
    if (user) {
      thet.setData({
        isLoge: true,
        user: user,
        // inspiration: this.getTelepathy()
      })
      if (this.data.active === 2) {
        this.setData({
          tab1: "tab-item tab-left ",
          tab2: "tab-item tab-active",
          listData: [],
          leftList: [],
          rightList: [],
          pageIndex: 1,
          active: 2
        })
        this.init(2)
      }
      // 获取获赞和粉丝和关注
      myApi.getcount({
        ID: user.UserId
      }).then((res) => {

        thet.setData({
          attentionFansCollect: res.Result
        })

      })
      // 获取我的创作
      if (!this.data.id) {
        thet.setData({
          pageIndex: 1
        })
        thet.init(1)

      }
      thet.setData({
        id: user.UserId
      })
    } else {
      thet.setData({
        isLoge: false
      })
    }
    this.membershipLevel(user)
  },

  // 每次进入页面更新算力值
  async getTelepathy() {
    let useRes = await globalApi.getUserinfoForToken({
      ActivePort: 3
    })
    this.setData({
      inspiration: useRes.Result.Telepathy,
      // user: useRes.Result.VIPWeight

    })

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },



  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    if (this.data.lodding) {
      return
    } else {
      this.init(this.data.active)
    }

  },

  onShareAppMessage(e) {
    let id = e.target.dataset.id
    let title = e.target.dataset.title
    let imageUrl = e.target.dataset.img
    return {
      title,
      imageUrl,
      path: `pages/modelStore/modelDetail/index?id=${id}`,
    }
  },
})